package com.yixuan.mt.common.pool;

import com.yixuan.mt.common.cache.EventsCache;
import com.yixuan.mt.common.entity.Objects;
import com.yixuan.mt.common.pojo.EventsCachedData;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

@Component
public class EventsConnectionManage {

    private final List<Objects> eventsList = new LinkedList<>();

    @Autowired
    private EventsCache eventsCache;

    @PostConstruct
    public void init() {
        // 开启新线程
        new Thread(() -> {
            while (true) {
                for (EventsCachedData eventsCachedData : eventsCache.getEventsCachedDataList()) {
                    eventsCachedData.getDestination().test();
                }
                // 处理事件
                while (!eventsList.isEmpty()) {
                    Objects objects = eventsList.remove(0);
                    for (EventsCachedData eventsCachedData : eventsCache.getEventsCachedDataList()) {
                        if (eventsCachedData.getDestination().isAlive()) {
                            eventsCachedData.getDestination().send(objects);
                        }
                    }
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }
            }
        }).start();
    }

    public void sendEvents(Objects objects) {
        eventsList.add(objects);
    }
}
